package com.mjfeed.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mjfeed.Constants;
import com.mjfeed.entity.IndexImage;
import com.mjfeed.service.IndexImageService;
import com.mjfeed.dao.IndexImageDao;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;
import com.mjfeed.util.QueryCondition;

@Service("indexImageService")
public class IndexImageServiceImpl extends BaseServiceImpl implements IndexImageService {
	@Resource(name="indexImageDao")
    private IndexImageDao indexImageDao;
    
    @Transactional(readOnly = true)
	public Pagination<IndexImage> getPagination(ParamBean paramBean) {
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		if (StringUtils.isNotBlank(paramBean.getKeyword())) {
			queryConditions.add(new QueryCondition(paramBean.getField(), QueryCondition.LK, paramBean.getKeyword()));
		}
		String orderBy = "order by type asc,orders asc";
		Pagination<IndexImage> pagination = (Pagination<IndexImage>)getPagination(IndexImage.class, queryConditions, orderBy, paramBean.getPage(), paramBean.getPageSize());
		pagination.setPageHtml(paramBean.getUrl());
		return pagination;
	}
    
    public void build(IndexImage indexImage) {
		MultipartFile multipartFile = indexImage.getFile();
		if (multipartFile != null && !multipartFile.isEmpty()) {
			try {
				String uploadPath = Constants.UPLOAD_PATH_PREFIX_INDEXIMAGE + DateFormatUtils.format(new Date(), "yyyyMMdd")+"/";
				String uuid = UUID.randomUUID().toString();
				String sourcePath = uploadPath + uuid + FilenameUtils.EXTENSION_SEPARATOR + FilenameUtils.getExtension(multipartFile.getOriginalFilename());

				File sourceFile = new File(sourcePath);
				if (!sourceFile.getParentFile().exists()) {
					sourceFile.getParentFile().mkdirs();
				}
				multipartFile.transferTo(sourceFile);
				indexImage.setSource(sourcePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

    @Transactional(readOnly = true)
	public List<IndexImage> getAllIndexImage() {
    	String orderBy = "order by type asc,orders asc";
		return get(IndexImage.class, null, orderBy);
	}
}
